//
//  LGTApplyBegVC.swift
//  KJLGT
//
//  Created by jenkin on 2019/9/9.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit
import WisdomHUD

class LGTApplyBegVC: LGTBaseVC, PhotoDelegate, HJImageBrowserDelegate{

    var textView:LGTInputTextView?
    var orderModel:TaskOrderModel?
    var addImage:UIImageView?
    var clickInfoBlock:ClickInfoBlock? //保存回掉
    var selectImageInfo:Dictionary<String, Any>?
    var selectImage:UIImage?
    private var _info:Dictionary<String, Any>?
    var photoManager:PhotoManager? = {
        let photoManagr1 = PhotoManager()
        photoManagr1.needImages = true //需要上传多张图片
        photoManagr1.maxImageCount = 3 //最多选择三张图片
        return photoManagr1
    }()
    var upload:Bool = false //是否需要上传
    var addImageView:LGTSelectImageView? //上传图片视图
    var imageClickBlock:ClickIndexViewBlock?
    let imageMaxCount = 3
    //存放图片
    var imageArray:Array<UIImage> = []
//    var imageSourceArray:Array<String> = []
    var imageID:String = ""
    
    //初始化信息
    var info:Dictionary<String, Any>?{
        get{
            return _info
        }set{
            _info = newValue
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setBlock()
    }
    
    func setBlock(){
        //图片点击 最多三张
        weak var weakSelf = self
        self.imageClickBlock = {(tag:Int, view:UIView) in
            //添加图片
            if tag == weakSelf?.imageMaxCount{
                weakSelf?.addImageAction()
            }
                //图片浏览
            else{
                if weakSelf?.imageArray.count == 0{
                    return
                }
                
                let bview = HJImageBrowser.brower(frame: CGRect.init(), isEdit: true, isFilePath: true)
                bview.delegate = weakSelf
                bview.bottomView = view
                bview.indexImage = 0
                bview.defaultImage = getColorImageWithColor()
                bview.arrayImage = weakSelf?.imageArray
                bview.show()
            }
        }
        self.addImageView!.clickAction = self.imageClickBlock
    }
    
    override func setUI() {
        super.setUI()
        self.view.backgroundColor = BlackAlphaColor
        let backView:UIImageView = LGTViewCreateUtil.share.createImageViewCorner(corner: SizeFitFloat(10))
        self.view.addSubview(backView)
        backView.isUserInteractionEnabled = true
        backView.backgroundColor = UIColor.white
        backView.snp.makeConstraints { (make) in
            make.center.equalTo(self.view)
            make.width.equalTo(SizeFit(303))
            make.height.equalTo(SizeFit(493))
        }
        
        let data:Array<Dictionary<String, Any>> = [["title":"申请申诉",
                                                    "subtitle":"验证图*",
                                                    "place1":"请输入原因"]
        ]
        
        let info:Dictionary<String, Any> = data[0]
        let title:String = info["title"] as! String
        let subtitle:String = info["subtitle"] as! String
        let place1:String = info["place1"] as! String
        
        let titleLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: 0, text: title)
        backView.addSubview(titleLabel)
        
        titleLabel.font = UIFont.boldSystemFont(ofSize: SizeFitFloat(18))
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(backView)
            make.height.equalTo(SizeFit(18))
            make.top.equalTo(SizeFit(22))
        }
        
        let clostBtn = LGTViewCreateUtil.share.createLGTButton(image: "close_icon", selected: "close_icon", dW: SizeFitFloat(10), dH: SizeFitFloat(10))
        backView.addSubview(clostBtn)
        clostBtn.snp.makeConstraints { (make) in
            make.width.height.equalTo(SizeFit(13))
            make.top.equalTo(SizeFit(23))
            make.right.equalTo(-SizeFit(24))
        }
        
        let descLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: SizeFitFloat(15), text: "填写申诉理由*")
        BaseUtil.setLabelSpecial(label: descLabel, str: "填写申诉理由*", specialStr: "*", normalAttr: [NSAttributedString.Key.foregroundColor:TextColor], specialAttr: [NSAttributedString.Key.foregroundColor:ColorUtil(color: 0xFF0101)
            ])
        backView.addSubview(descLabel)
        descLabel.snp.makeConstraints { (make) in
            make.left.equalTo(SizeFit(27))
            make.top.equalTo(SizeFit(59))
            make.height.equalTo(SizeFitFloat(15))
        }
        
        let imageView:UIImageView = LGTViewCreateUtil.share.createImageViewCorner(corner: SizeFitFloat(3))
        imageView.isUserInteractionEnabled = true
        imageView.backgroundColor = ViewBackColor
        backView.addSubview(imageView)
        imageView.snp.makeConstraints { (make) in
            make.centerX.equalTo(backView)
            make.height.equalTo(SizeFitFloat(102))
            make.width.equalTo(SizeFitFloat(252))
            make.top.equalTo(SizeFit(84))
        }
        
        self.textView = LGTViewCreateUtil.share.createInputTextView(placehoder: place1, fontSize: SizeFitFloat(12), limitCout: 200)
        imageView.addSubview(self.textView!)
        self.textView?.textView.backgroundColor = UIColor.clear
        self.textView?.textView.isScrollEnabled = true
        self.textView?.showCount = true
        self.textView?.backgroundColor = UIColor.clear
        self.textView!.snp.makeConstraints({ (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(SizeFit(10))
            make.width.equalTo(SizeFitFloat(230))
            make.bottom.equalTo(SizeFit(-18))
        })
        
        let titleLabel2:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: SizeFitFloat(15), text: subtitle)
        backView.addSubview(titleLabel2)
        //titleLabel2.font = UIFont.boldSystemFont(ofSize: SizeFitFloat(18))
        titleLabel2.snp.makeConstraints { (make) in
            make.left.equalTo(SizeFit(27))
            make.height.equalTo(SizeFit(15))
            make.top.equalTo(SizeFit(205))
        }
        
        BaseUtil.setLabelSpecial(label: titleLabel2, str: subtitle, specialStr: "*", normalAttr: [NSAttributedString.Key.foregroundColor:TextColor], specialAttr: [NSAttributedString.Key.foregroundColor:ColorUtil(color: 0xFF0101)
            ])
        
//        self.addImage = LGTViewCreateUtil.share.createImageView(image: "addto")
//        self.addImage?.layer.masksToBounds = true
//        backView.addSubview(self.addImage!)
//        self.addImage?.isUserInteractionEnabled = true
//        let tap:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self
//            , action: #selector(addImageAction))
//        self.addImage?.addGestureRecognizer(tap)
//        self.addImage!.snp.makeConstraints({ (make) in
//            make.left.equalTo(SizeFit(27))
//            make.width.height.equalTo(SizeFit(80))
//            make.top.equalTo(SizeFit(235))
//        })
        
        //添加图片视图
        let imageW:CGFloat = SizeFitFloat(80)
        let space:CGFloat = SizeFitFloat(5)
        self.addImageView = LGTSelectImageView.initWithImages(images: [], maxCount: imageMaxCount, imageW: imageW, space: space, rowCount: 3)
        backView.addSubview(self.addImageView!)
        self.addImageView!.snp.makeConstraints { (make) in
            make.left.equalTo(SizeFit(27))
            make.height.equalTo(SizeFit(80))
            make.right.equalTo(0)
            make.top.equalTo(SizeFit(235))
        }
        
        let sureButton:UIButton = LGTViewCreateUtil.share.createTextLGTButton(title: "确认申诉", font: Font_Normal_15, color: UIColor.white, selectedColor: UIColor.white, corner:SizeFitFloat(20), backColor: YellowColor)
        backView.addSubview(sureButton)
        sureButton.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.height.equalTo(SizeFit(40))
            make.width.equalTo(SizeFit(252))
            make.top.equalTo(SizeFit(395))
        }
        
        let cancelBtn:UIButton = LGTViewCreateUtil.share.createTextLGTButton(title: "取消", font: Font_Normal_15, color: YellowColor, selectedColor: YellowColor, corner:SizeFitFloat(20), backColor: UIColor.clear)
        backView.addSubview(cancelBtn)
        cancelBtn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.height.equalTo(SizeFit(40))
            make.width.equalTo(SizeFit(252))
            make.top.equalTo(sureButton.snp_bottomMargin).offset(SizeFit(10))
        }
        cancelBtn.addTarget(self, action: #selector(closeAction), for: UIControl.Event.touchUpInside)
        clostBtn.addTarget(self, action: #selector(closeAction), for: UIControl.Event.touchUpInside)
        sureButton.addTarget(self, action: #selector(sureAction), for: UIControl.Event.touchUpInside)
        
        if self.info != nil {
            self.textView?.text = self.info?["stepText"] as? String ?? ""
            let selectInfo:Dictionary<String, Any>? = self.info?["selectInfo"] as! Dictionary<String, Any>
            let url:String = selectInfo?["url"] as? String ?? ""
            //self.addImage?.sd_setImage(with: URL.init(string: url), placeholderImage: UIImage.init(named: ""), options: SDWebImageOptions.retryFailed, context: nil)
            BaseUtil.baseUtil.setImage(imageView: self.addImage!, imageUrl: url, type: .BigImageType)
        }
    }
    
    @objc func addImageAction(){
        print("addImage")
        //都不做裁剪
        self.photoManager?.unNeedCrop = true
        self.photoManager?.delegate = self as PhotoDelegate
        let alertVC = UIAlertController.init(title: "获取方式", message: "", preferredStyle: UIAlertController.Style.actionSheet)
        weak var weakSelf = self
        let playAction = UIAlertAction.init(title: "拍照", style: UIAlertAction.Style.default) { (action) in
            weakSelf?.photoManager?.actionSheet(UIActionSheet(), clickedButtonAt: 0)
        }
        let ablumAction = UIAlertAction.init(title: "从相册中选择", style: UIAlertAction.Style.default) { (action) in
            weakSelf?.photoManager?.actionSheet(UIActionSheet(), clickedButtonAt: 1)
        }
        let cancelAction = UIAlertAction.init(title: "取消", style: UIAlertAction.Style.cancel) { (action) in
            
        }
        alertVC.addAction(playAction)
        alertVC.addAction(ablumAction)
        alertVC.addAction(cancelAction)
        self.present(alertVC, animated: true, completion: nil)
    }
    
    @objc func closeAction(){
        print("closeAction")
        self.dismiss(animated: false, completion: nil)
    }
    
    @objc func sureAction(){
        //if self.textView?.textView.text.count == 0 && self.selectImage == nil{
        if self.textView?.textView.text.count == 0{
            //WisdomHUD.showText(text: "请输入申诉理由或验证图")
            WisdomHUD.showText(text: "请输入申诉理由")
            return
        }
        
        self.imageID = ""
        //上传图片
        if self.imageArray.count != 0{
            self.uploadImage(index: 0)
        }else{
            //提交申诉
            self.refuseAction()
        }
        
//        //上传图片
//        let message:String = self.textView?.textView.text ?? ""
//        if self.selectImage != nil{
//            let data:Data = self.selectImage?.jpegData(compressionQuality: 0.8) ?? Data()
//            let param:Dictionary<String, Any> = ["image":data]
//            weak var weakSelf = self
//            WisdomHUD.showLoading()
//            LGTHttpUtil.httpUtil.uploadData(url: Upload_Image_URL, param: param, success: { (json) in
//                let data:Dictionary<String, Any> = json["data"] as? Dictionary<String, Any> ?? [:]
//                let imageID:String = "\(data["id"] as? Int ?? 0)"
//                let param:Dictionary<String, Any> = ["image": imageID,
//                                                     "id": weakSelf?.orderModel?.id ?? 0,
//                                                     "status": 8,
//                                                     "message":message]
//                //提交申诉
//                weakSelf?.refuseAction(param: param)
//            }) { (json) in
//                WisdomHUD.dismiss()
//                WisdomHUD.showError(text: json["message"] as? String ?? "")
//            }
//        }else{
//            let param:Dictionary<String, Any> = [
//                "id": self.orderModel?.id ?? 0,
//                "status": 8,
//                "message":message]
//            //提交申诉
//            self.refuseAction(param: param)
//        }
    }
    
    //上传图片
    func uploadImage(index:Int){
        //上传结束
        if index >= self.imageArray.count{
            WisdomHUD.dismiss()
            //拒绝
            self.refuseAction()
            return
        }
        
        if index > 0{
            self.imageID.append(",")
        }
        
        //上传图片中
        let image:UIImage = self.imageArray[index]
        let data:Data = image.jpegData(compressionQuality: 0.8) ?? Data()
        let param:Dictionary<String, Any> = ["image":data]
        weak var weakSelf = self
        WisdomHUD.showLoading()
        LGTHttpUtil.httpUtil.uploadData(url: Upload_Image_URL, param: param, success: { (json) in
            let data:Dictionary<String, Any> = json["data"] as? Dictionary<String, Any> ?? [:]
            let imageID:String = "\(data["id"] as? Int ?? 0)"
            weakSelf?.imageID.append(imageID)
            //继续上传
            weakSelf?.uploadImage(index: index+1)
        }) { (json) in
            WisdomHUD.dismiss()
            WisdomHUD.showError(text: json["message"] as? String ?? "")
        }
    }
    
    //提交申诉
    func refuseAction(){
        let message:String = self.textView?.textView.text ?? ""
        let param:Dictionary<String, Any> = [
            "id": self.orderModel?.id ?? 0,
            "status": 8,
            "message":message]
        
        weak var weakSelf = self
        LGTHttpUtil.httpUtil.requestData(url: LLZ_OrderStatus_Update_URL, param: param, showMessage: true, success: { (json) in
            weakSelf?.dismiss(animated: false, completion: nil)
            if weakSelf?.clickInfoBlock != nil{
                weakSelf?.clickInfoBlock!(0, json)
            }
        }) { (json) in
        }
    }
    
    //裁剪图片代理
    func imageCropper(_ cropperViewController: VPImageCropperViewController, didFinished editedImage: UIImage) {
//        self.upload = true
//        self.selectImage = BaseUtil.baseUtil.getUploadImage(editedImage: editedImage)
//        self.addImage?.image = self.selectImage
//        if cropperViewController != nil{
//            cropperViewController.dismiss(animated: true, completion: nil)
//        }
    }
    
    //选择多张图片返回处理
    func imageCropperSelectImages(_ images: [Any]!, sourceAssets assets: [Any]!) {
//        let  currentAssets:Array<PHAsset> = assets as? Array<PHAsset> ?? []
//        weak var weakSelf = self
//        for p in currentAssets{
//            PHCachingImageManager.default().requestImageData(for: p, options: nil) { (data, url, or, info) in
//                if info != nil{
//                    let url:NSString? = (info?["PHImageFileSandboxExtensionTokenKey"] as? NSString)
//                    let dataArray = url?.components(separatedBy: ";")
//                    if dataArray?.count ?? 0 > 0{
//                        weakSelf?.imageSourceArray.append(dataArray!.last!)
//                    }
//                }
//            }
//        }
//
//        for i in 0..<images.count{
//            let image:UIImage? = images[i] as? UIImage
//            if image != nil{
//                self.imageArray.append(BaseUtil.baseUtil.getUploadImage(editedImage: image!))
//            }
//        }
        self.imageArray = images as? Array<UIImage> ?? []
        self.addImageView?.imagesArray = self.imageArray
    }
    
    func imageCropperDidCancel(_ cropperViewController: VPImageCropperViewController!) {
        cropperViewController.dismiss(animated: true, completion: nil)
    }
    
    func finish(_ controller: UIViewController!) {
        self.present(controller, animated: true, completion: nil)
    }
    
    func getCropSize() -> CGRect {
        return CGRect.init(x: 0, y: (KScreenH - KScreenW)/2, width: KScreenW, height: KScreenW)
    }
    
    //HJImageBrowserDelegate
    func getTheThumbnailImage(_ indexRow: Int) -> UIImage {
        return UIImage.init()
    }
    
    func imageSelectComplete(images: Array<Any>) {
//        //每个图片索引位置
//        var data:Array<Int> = []
//        for image in images{
//            for i in 0..<self.imageSourceArray.count{
//                let image2:String = self.imageSourceArray[i]
//                if image == image2{
//                    data.append(i)
//                    break
//                }
//            }
//        }
//        self.imageSourceArray = images
//
//        var imageArray:Array<UIImage> = []
//        for i in 0..<data.count{
//            let index = data[i]
//            let image = self.imageArray[index]
//            imageArray.append(image)
//        }
        self.imageArray = images as? Array<UIImage> ?? []
        self.addImageView?.imagesArray = self.imageArray
    }
}
